package com.dcrzl.shcz.module.common.service.impl;

import com.dcrzl.shcz.common.exception.MyException;
import com.dcrzl.shcz.common.utils.Result;
import com.dcrzl.shcz.common.utils.SysConstant;
import com.dcrzl.shcz.module.common.service.CaptchaService;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

@Service("captchaService")
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public BufferedImage getCaptcha(String uuid) {
        if (StringUtils.isEmpty(uuid)) {
            throw new MyException("uuid不能为空");
        }
        //生成文字验证码
        String code = captchaProducer.createText();
        stringRedisTemplate.opsForValue().set(uuid, code,
                SysConstant.CAPTCHA_CODE_EXP_TIME, TimeUnit.SECONDS);
        return captchaProducer.createImage(code);
    }

    @Override
    public Result<String> validate(String uuid, String code) {
        String s = stringRedisTemplate.opsForValue().get(uuid);
        Result<String> resultEntity = new Result<>();
        if (StringUtils.isEmpty(s)){
            return resultEntity.setSuccess(false)
                    .setMsg("验证码已过期").setCode(SysConstant.CODE_EXPIRE_CODE_RES);
        }else{
            if (s.equalsIgnoreCase(code)){
                return resultEntity.setSuccess(true);
            }else{
                return resultEntity.setSuccess(false)
                        .setMsg("验证码不正确").setCode(SysConstant.CODE_ERROR_CODE_RES);
            }
        }
    }
}
